package cn.eu.common.query.model;

import cn.eu.common.query.annotation.Condition;
import cn.eu.common.query.annotation.Query;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;

@Setter
@Getter
public class ConditionModel {

    private Query.Type type;

    private String leftAlias;

    private String leftField;

    private String rightAlias;

    private String rightField;

    private Object value;

    public ConditionModel(TableInfo tableInfo, String tableAlias, Condition condition) {
        this.leftAlias = StrUtil.blankToDefault(condition.alias(), tableAlias);
        String thisField = condition.field();
        this.leftField = tableInfo.getFieldList().stream().filter(field -> field.getProperty().equals(thisField))
                .findFirst().orElseThrow(() -> new RuntimeException(StrUtil.format("数据表不存在属性[{}]", thisField)))
                .getColumn();
        this.type = condition.type();
    }

    public ConditionModel(Map<String, TableModel> tableModelMap, String tableAlias, Condition condition) {
        String alias = StrUtil.blankToDefault(condition.alias(), tableAlias);
        if(!tableModelMap.containsKey(alias)) throw new RuntimeException(StrUtil.format("表别名不存在[{}]", alias));
        this.leftAlias = alias;
        String thisField = condition.field();
        this.leftField = tableModelMap.get(alias).getTable().getFieldList().stream().filter(field -> field.getProperty().equals(thisField))
                .findFirst().orElseThrow(() -> new RuntimeException(StrUtil.format("数据表不存在属性[{}]", thisField)))
                .getColumn();
        this.type = condition.type();
    }

    public ConditionModel(Map<String, TableModel> tableModelMap,
                          Query.Type type,
                          String leftAlias,
                          String leftField) {
        if(!tableModelMap.containsKey(leftAlias)) throw new RuntimeException(StrUtil.format("表别名不存在[{}]", leftAlias));
        this.leftAlias = leftAlias;
        this.leftField = tableModelMap.get(leftAlias).getTable().getFieldList().stream().filter(field -> field.getProperty().equals(leftField))
                .findFirst().orElseThrow(() -> new RuntimeException(StrUtil.format("数据表不存在属性[{}]", leftField)))
                .getColumn();
        this.type = type;
    }

    public ConditionModel(TableModel left, TableModel right) {
        this.type = Query.Type.APPLY;
        this.leftAlias = left.getAlias();
        this.leftField = left.getJoinField();
        this.rightAlias = right.getAlias();
        this.rightField = right.getJoinField();
    }

    public String getLeftColumn() {
        return StrUtil.format("{}.{}", leftAlias, leftField);
    }
}
